/**    
 * @{#} RecordingUtil.java Create on 2014年7月15日 下午9:02:17    
 *    
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.evan.common.utils;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OutputFormat;
import android.util.Log;

public class RecordingUtil {

	private File recordFile;

	private MediaRecorder mr;
	private static boolean isRun;

	private String voicePath;
	private int time;
	private Activity activity;

	public RecordingUtil(Activity activity) {
		this.activity = activity;
	}

	@SuppressWarnings("deprecation")
	public void startRecord(String path) {
		this.voicePath = path;
		if (!CommonUtility.isNull(voicePath)) {
			recordFile = new File(voicePath);

			if (recordFile.exists()) {
				
				recordFile.delete();
			}
			try {
				recordFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				mr = new MediaRecorder();
				mr.setAudioSource(MediaRecorder.AudioSource.MIC);
				mr.setOutputFormat(OutputFormat.RAW_AMR);
				mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
				mr.setOutputFile(voicePath);
				
				mr.prepare();
				mr.start();
				isRun = true;
				new Thread() {
					public void run() {
						while (isRun) {
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							time++;
						}
					}
				}.start();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		} else {
			CommonUtility.toast(activity, "初始化文件失败，请重新登录后再试");
		}
	}

	public void startRecord() {
		this.voicePath = FilesUtil.getTempVoicePath();
		startRecord(voicePath);
	}

	public void stopRecord() {
		try {
			if (mr == null) {
				return;
			}
			isRun = false;
			mr.stop();
			mr.release();
			mr = null;
		} catch (Exception e) {
			// TODO: handle exception
			isRun = false;
			e.printStackTrace();
		}
	}

	public void deleteRecordFile() {
		if (!CommonUtility.isNull(recordFile) && recordFile.isFile()) {
			recordFile.delete();
		}
	}

	public String getVoicePath() {
		return this.voicePath;
	}

	public int getVoiceTime() {
		return time;
	}

	public boolean isRecording() {
		return isRun;
	}

	public int getVolume() {
		try {
			if (!CommonUtility.isNull(mr)) {
				return (mr.getMaxAmplitude());
			} else
				return 0;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return 0;
	}
}
